package org.boyan.modules.cgform.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.boyan.common.system.api.ISysBaseAPI;
import org.boyan.common.system.vo.DictModel;
import org.boyan.common.system.vo.LoginUser;
import org.boyan.common.util.oConvertUtils;
import org.boyan.modules.auth.service.IOnlAuthPageService;
import org.boyan.modules.cgform.a.a;
import org.boyan.modules.cgform.entity.OnlCgformButton;
import org.boyan.modules.cgform.entity.OnlCgformEnhanceJs;
import org.boyan.modules.cgform.entity.OnlCgformField;
import org.boyan.modules.cgform.entity.OnlCgformHead;
import org.boyan.modules.cgform.model.HrefSlots;
import org.boyan.modules.cgform.model.OnlColumn;
import org.boyan.modules.cgform.model.OnlComplexModel;
import org.boyan.modules.cgform.model.b;
import org.boyan.modules.cgform.model.d;
import org.boyan.modules.cgform.model.f;
import org.boyan.modules.cgform.service.IOnlCgformFieldService;
import org.boyan.modules.cgform.service.IOnlCgformHeadService;
import org.boyan.modules.cgform.service.IOnlineService;
import org.boyan.modules.cgform.util.EnhanceJsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service("onlineService")
public class k implements IOnlineService {
    @Autowired
    private IOnlCgformFieldService onlCgformFieldService;

    @Autowired
    private IOnlCgformHeadService onlCgformHeadService;

    @Autowired
    private ISysBaseAPI sysBaseAPI;

    @Autowired
    private IOnlAuthPageService onlAuthPageService;

    public OnlComplexModel queryOnlineConfig(OnlCgformHead head, String username) {
        String str = head.getId();
        boolean bool = org.boyan.modules.cgform.util.b.a(head);
        List<OnlCgformField> list = b(str);
        List<String> list1 = this.onlAuthPageService.queryHideCode(str, true);
        ArrayList<OnlColumn> arrayList = new ArrayList<>();
        HashMap<String, List<DictModel>> hashMap1 = new HashMap<>();
        ArrayList<HrefSlots> arrayList1 = new ArrayList<>();
        ArrayList<b> arrayList2 = new ArrayList<>();
        ArrayList<String> arrayList3 = new ArrayList<>();
        HashMap<String, Object> hashMap2 = new HashMap<>();
        for (OnlCgformField onlCgformField : list) {
            String str1 = onlCgformField.getDbFieldName();
            String str2 = onlCgformField.getMainTable();
            String str3 = onlCgformField.getMainField();
            if (oConvertUtils.isNotEmpty(str3) && oConvertUtils.isNotEmpty(str2)) {
                b b = new b(str1, str3);
                arrayList2.add(b);
            }
            if (1 != onlCgformField.getIsShowList())
                continue;
            if ("id".equals(str1))
                continue;
            if (list1.contains(str1))
                continue;
            if (arrayList3.contains(str1))
                continue;
            OnlColumn onlColumn = a(onlCgformField, hashMap1, arrayList1);
            String str4 = onlColumn.getLinkField();
            if (str4 != null && !"".equals(str4))
                a(list, arrayList3, arrayList, str1, str4);
            hashMap2.put(onlCgformField.getDbFieldName(), 1);
            arrayList.add(onlColumn);
        }
        if (bool) {
            List<OnlColumn> list3 = a(head, hashMap1, arrayList1, (Map)hashMap2);
            if (list3.size() > 0) {
                ArrayList<String> arrayList5 = new ArrayList<>();
                for (String str1 : hashMap2.keySet()) {
                    if ((Integer) hashMap2.get(str1) > 1)
                        arrayList5.add(str1);
                }
                for (OnlColumn onlColumn : list3) {
                    String str1 = onlColumn.getDataIndex();
                    if (arrayList5.contains(str1))
                        onlColumn.setDataIndex(onlColumn.getTableName() + "_" + str1);
                    arrayList.add(onlColumn);
                }
            }
        }
        OnlComplexModel onlComplexModel = new OnlComplexModel();
        onlComplexModel.setCode(str);
        onlComplexModel.setTableType(head.getTableType());
        onlComplexModel.setFormTemplate(head.getFormTemplate());
        onlComplexModel.setDescription(head.getTableTxt());
        onlComplexModel.setCurrentTableName(head.getTableName());
        onlComplexModel.setPaginationFlag(head.getIsPage());
        onlComplexModel.setCheckboxFlag(head.getIsCheckbox());
        onlComplexModel.setScrollFlag(head.getScroll());
        onlComplexModel.setRelationType(head.getRelationType());
        onlComplexModel.setColumns(arrayList);
        onlComplexModel.setDictOptions(hashMap1);
        onlComplexModel.setFieldHrefSlots(arrayList1);
        onlComplexModel.setForeignKeys(arrayList2);
        onlComplexModel.setHideColumns(list1);
        List<OnlCgformButton> list2 = this.onlCgformHeadService.queryButtonList(str, true);
        ArrayList<OnlCgformButton> arrayList4 = new ArrayList<>();
        for (OnlCgformButton onlCgformButton : list2) {
            if (list1.contains(onlCgformButton.getButtonCode()))
                continue;
            arrayList4.add(onlCgformButton);
        }
        onlComplexModel.setCgButtonList(arrayList4);
        OnlCgformEnhanceJs onlCgformEnhanceJs = this.onlCgformHeadService.queryEnhanceJs(str, "list");
        if (onlCgformEnhanceJs != null && oConvertUtils.isNotEmpty(onlCgformEnhanceJs.getCgJs())) {
            String str1 = EnhanceJsUtil.b(onlCgformEnhanceJs.getCgJs(), list2);
            onlComplexModel.setEnhanceJs(str1);
        }
        if ("Y".equals(head.getIsTree())) {
            onlComplexModel.setPidField(head.getTreeParentIdField());
            onlComplexModel.setHasChildrenField(head.getTreeIdField());
            onlComplexModel.setTextField(head.getTreeFieldname());
        }
        return onlComplexModel;
    }

    private String[] a(String paramString) {
        String[] arrayOfString = { "", "" };
        if (paramString != null && !"".equals(paramString)) {
            JSONObject jSONObject = JSON.parseObject(paramString);
            if (jSONObject.containsKey("store"))
                arrayOfString[0] = oConvertUtils.camelToUnderline(jSONObject.getString("store"));
            if (jSONObject.containsKey("text"))
                arrayOfString[1] = oConvertUtils.camelToUnderline(jSONObject.getString("text"));
        }
        return arrayOfString;
    }

    private void a(List<OnlCgformField> paramList, List<String> paramList1, List<OnlColumn> paramList2, String paramString1, String paramString2) {
        if (oConvertUtils.isNotEmpty(paramString2)) {
            String[] arrayOfString = paramString2.split(",");
            for (String str : arrayOfString) {
                for (OnlCgformField onlCgformField : paramList) {
                    String str1 = onlCgformField.getDbFieldName();
                    if (1 != onlCgformField.getIsShowList())
                        continue;
                    if (str.equals(str1)) {
                        paramList1.add(str);
                        OnlColumn onlColumn = new OnlColumn(onlCgformField.getDbFieldTxt(), str1);
                        onlColumn.setCustomRender(paramString1);
                        paramList2.add(onlColumn);
                        break;
                    }
                }
            }
        }
    }

    public JSONObject queryOnlineFormObj(OnlCgformHead head, OnlCgformEnhanceJs onlCgformEnhanceJs) {
        JSONObject jSONObject1 = new JSONObject();
        String str1 = head.getId();
        String str2 = head.getTaskId();
        List<OnlCgformField> list = this.onlCgformFieldService.queryAvailableFields(str1, head.getTableName(), str2, false);
        ArrayList<String> arrayList = new ArrayList<>();
        if (oConvertUtils.isEmpty(str2)) {
            List<String> list2 = this.onlAuthPageService.queryFormDisabledCode(head.getId());
            if (list2 != null && list2.size() > 0 && list2.get(0) != null)
                arrayList.addAll(list2);
        } else {
            List<String> list2 = this.onlCgformFieldService.queryDisabledFields(head.getTableName(), str2);
            if (list2 != null && list2.size() > 0 && list2.get(0) != null)
                arrayList.addAll(list2);
        }
        EnhanceJsUtil.a(onlCgformEnhanceJs, head.getTableName(), list);
        f f = null;
        if ("Y".equals(head.getIsTree())) {
            f = new f();
            f.setCodeField("id");
            f.setFieldName(head.getTreeParentIdField());
            f.setPidField(head.getTreeParentIdField());
            f.setPidValue("0");
            f.setHsaChildField(head.getTreeIdField());
            f.setTableName(org.boyan.modules.cgform.util.b.f(head.getTableName()));
            f.setTextField(head.getTreeFieldname());
        }
        JSONObject jSONObject2 = org.boyan.modules.cgform.util.b.a(list, arrayList, f);
        jSONObject2.put("table", head.getTableName());
        jSONObject2.put("describe", head.getTableTxt());
        jSONObject1.put("schema", jSONObject2);
        jSONObject1.put("head", head);
        List<OnlCgformButton> list1 = queryFormValidButton(str1);
        if (list1 != null && list1.size() > 0)
            jSONObject1.put("cgButtonList", list1);
        if (onlCgformEnhanceJs != null && oConvertUtils.isNotEmpty(onlCgformEnhanceJs.getCgJs())) {
            String str = EnhanceJsUtil.c(onlCgformEnhanceJs.getCgJs(), list1);
            onlCgformEnhanceJs.setCgJs(str);
            jSONObject1.put("enhanceJs", EnhanceJsUtil.a(onlCgformEnhanceJs.getCgJs()));
        }
        return jSONObject1;
    }

    @Cacheable(value = {"sys:cache:online:form"}, key = "'erp'+ #head.id+'-'+#username")
    public JSONObject queryOnlineFormObj(OnlCgformHead head, String username) {
        OnlCgformEnhanceJs onlCgformEnhanceJs = this.onlCgformHeadService.queryEnhanceJs(head.getId(), "form");
        return queryOnlineFormObj(head, onlCgformEnhanceJs);
    }

    public List<OnlCgformButton> queryFormValidButton(String headId) {
        List<OnlCgformButton> list = this.onlCgformHeadService.queryButtonList(headId, false);
        List<OnlCgformButton> list1 = null;
        if (list != null && list.size() > 0) {
            LoginUser loginUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
            String str = loginUser.getId();
            List<String> list2 = this.onlAuthPageService.queryFormHideButton(str, headId);
            list1 = (List)list.stream().filter(paramOnlCgformButton -> (list2 == null || list2.indexOf(paramOnlCgformButton.getButtonCode()) < 0)).collect(Collectors.toList());
        }
        return list1;
    }

    @Cacheable(value = {"sys:cache:online:form"}, key = "#head.id+'-'+#username")
    public JSONObject queryOnlineFormItem(OnlCgformHead head, String username) {
        head.setTaskId(null);
        return a(head);
    }

    @Cacheable(value = {"sys:cache:online:form"}, key = "'flow' + #head.id + '-' + #username + '-' + #taskId")
    public JSONObject queryFlowOnlineFormItem(OnlCgformHead head, String username, String taskId) {
        head.setTaskId(taskId);
        return a(head);
    }

    @Cacheable(value = {"sys:cache:online:form"}, key = "'enhancejs' + #code + '-' + #type")
    public String queryEnahcneJsString(String code, String type) {
        String str = "";
        OnlCgformEnhanceJs onlCgformEnhanceJs = this.onlCgformHeadService.queryEnhanceJs(code, type);
        if (onlCgformEnhanceJs != null && oConvertUtils.isNotEmpty(onlCgformEnhanceJs.getCgJs()))
            str = EnhanceJsUtil.b(onlCgformEnhanceJs.getCgJs(), (List)null);
        return str;
    }

    private List<OnlCgformField> b(String paramString) {
        LambdaQueryWrapper<OnlCgformField> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OnlCgformField::getCgformHeadId, paramString);
        lambdaQueryWrapper.orderByAsc(OnlCgformField::getOrderNum);
        return this.onlCgformFieldService.list(lambdaQueryWrapper);
    }

    private JSONObject a(OnlCgformHead paramOnlCgformHead) {
        OnlCgformEnhanceJs onlCgformEnhanceJs = this.onlCgformHeadService.queryEnhanceJs(paramOnlCgformHead.getId(), "form");
        JSONObject jSONObject = queryOnlineFormObj(paramOnlCgformHead, onlCgformEnhanceJs);
        jSONObject.put("formTemplate", paramOnlCgformHead.getFormTemplate());
        if (paramOnlCgformHead.getTableType() == 2) {
            JSONObject jSONObject1 = jSONObject.getJSONObject("schema");
            String str = paramOnlCgformHead.getSubTableStr();
            if (oConvertUtils.isNotEmpty(str)) {
                ArrayList<OnlCgformHead> arrayList = new ArrayList();
                for (String str1 : str.split(",")) {
                    OnlCgformHead onlCgformHead = this.onlCgformHeadService.getOne(
                            new LambdaQueryWrapper<OnlCgformHead>().eq(OnlCgformHead::getTableName, str1));
                    if (onlCgformHead != null)
                        arrayList.add(onlCgformHead);
                }
                if (arrayList.size() > 0) {
                    Collections.sort(arrayList, new Comparator<OnlCgformHead>() {
                        @Override
                        public int compare(OnlCgformHead param1OnlCgformHead1, OnlCgformHead param1OnlCgformHead2) {
                            Integer integer1 = param1OnlCgformHead1.getTabOrderNum();
                            if (integer1 == null)
                                integer1 = 0;
                            Integer integer2 = param1OnlCgformHead2.getTabOrderNum();
                            if (integer2 == null)
                                integer2 = 0;
                            return integer1.compareTo(integer2);
                        }
                    });
                    for (OnlCgformHead onlCgformHead : arrayList) {
                        List<OnlCgformField> list1 = this.onlCgformFieldService.queryAvailableFields(onlCgformHead.getId(), onlCgformHead.getTableName(), paramOnlCgformHead.getTaskId(), false);
                        EnhanceJsUtil.b(onlCgformEnhanceJs, onlCgformHead.getTableName(), list1);
                        JSONObject jSONObject2 = new JSONObject();
                        List<String> list2 = new ArrayList<>();
                        if (oConvertUtils.isNotEmpty(paramOnlCgformHead.getTaskId())) {
                            List<String> list = this.onlCgformFieldService.queryDisabledFields(onlCgformHead.getTableName(), paramOnlCgformHead.getTaskId());
                        } else {
                            list2 = this.onlAuthPageService.queryFormDisabledCode(onlCgformHead.getId());
                        }
                        if (1 == onlCgformHead.getRelationType()) {
                            jSONObject2 = org.boyan.modules.cgform.util.b.a(list1, list2, null);
                        } else {
                            jSONObject2.put("columns", org.boyan.modules.cgform.util.b.a(list1, list2));
                            List<String> list = this.onlAuthPageService.queryListHideButton(null, onlCgformHead.getId());
                            jSONObject2.put("hideButtons", list);
                        }
                        String str1 = this.onlCgformFieldService.queryForeignKey(onlCgformHead.getId(), paramOnlCgformHead.getTableName());
                        jSONObject2.put("foreignKey", str1);
                        jSONObject2.put("id", onlCgformHead.getId());
                        jSONObject2.put("describe", onlCgformHead.getTableTxt());
                        jSONObject2.put("key", onlCgformHead.getTableName());
                        jSONObject2.put("view", "tab");
                        jSONObject2.put("order", onlCgformHead.getTabOrderNum());
                        jSONObject2.put("relationType", onlCgformHead.getRelationType());
                        jSONObject2.put("formTemplate", onlCgformHead.getFormTemplate());
                        jSONObject1.getJSONObject("properties").put(onlCgformHead.getTableName(), jSONObject2);
                    }
                }
            }
            if (onlCgformEnhanceJs != null && oConvertUtils.isNotEmpty(onlCgformEnhanceJs.getCgJs()))
                jSONObject.put("enhanceJs", EnhanceJsUtil.a(onlCgformEnhanceJs.getCgJs()));
        }
        return jSONObject;
    }

    private OnlColumn a(OnlCgformField paramOnlCgformField, Map<String, List<DictModel>> paramMap, List<HrefSlots> paramList) {
        String str1 = paramOnlCgformField.getDbFieldName();
        OnlColumn onlColumn = new OnlColumn(paramOnlCgformField.getDbFieldTxt(), str1);
        String str2 = paramOnlCgformField.getDictField();
        String str3 = paramOnlCgformField.getFieldShowType();
        if (oConvertUtils.isNotEmpty(str2) && !"popup".equals(str3)) {
            List<DictModel> list = new ArrayList<>();
            if (oConvertUtils.isNotEmpty(paramOnlCgformField.getDictTable())) {
                List<DictModel> list1 = this.sysBaseAPI.queryTableDictItemsByCode(paramOnlCgformField.getDictTable(), paramOnlCgformField.getDictText(), str2);
            } else if (oConvertUtils.isNotEmpty(paramOnlCgformField.getDictField())) {
                list = this.sysBaseAPI.queryDictItemsByCode(str2);
            }
            paramMap.put(str1, list);
            onlColumn.setCustomRender(str1);
        }
        if ("switch".equals(str3)) {
            List<DictModel> list = org.boyan.modules.cgform.util.b.a(paramOnlCgformField);
            paramMap.put(str1, list);
            onlColumn.setCustomRender(str1);
        }
        if ("link_down".equals(str3)) {
            String str = paramOnlCgformField.getDictTable();
            a a = (a)JSONObject.parseObject(str, a.class);
            List<DictModel> list = this.sysBaseAPI.queryTableDictItemsByCode(a.getTable(), a.getTxt(), a.getKey());
            paramMap.put(str1, list);
            onlColumn.setCustomRender(str1);
        }
        if ("sel_tree".equals(str3)) {
            String[] arrayOfString = paramOnlCgformField.getDictText().split(",");
            List<DictModel> list = this.sysBaseAPI.queryTableDictItemsByCode(paramOnlCgformField.getDictTable(), arrayOfString[2], arrayOfString[0]);
            paramMap.put(str1, list);
            onlColumn.setCustomRender(str1);
        }
        if ("cat_tree".equals(str3)) {
            String str = paramOnlCgformField.getDictText();
            if (oConvertUtils.isEmpty(str)) {
                String str5 = org.boyan.modules.cgform.util.b.e(paramOnlCgformField.getDictField());
                List<DictModel> list = this.sysBaseAPI.queryFilterTableDictInfo("SYS_CATEGORY", "NAME", "ID", str5);
                paramMap.put(str1, list);
                onlColumn.setCustomRender(str1);
            } else {
                onlColumn.setCustomRender("_replace_text_" + str);
            }
        }
        if ("sel_depart".equals(str3)) {
            String[] arrayOfString = a(paramOnlCgformField.getFieldExtendJson());
            String str5 = (arrayOfString[0].length() > 0) ? arrayOfString[0] : "ID";
            String str6 = (arrayOfString[1].length() > 0) ? arrayOfString[1] : "DEPART_NAME";
            List<DictModel> list = this.sysBaseAPI.queryTableDictItemsByCode("SYS_DEPART", str6, str5);
            paramMap.put(str1, list);
            onlColumn.setCustomRender(str1);
        }
        if ("sel_user".equals(paramOnlCgformField.getFieldShowType())) {
            String[] arrayOfString = a(paramOnlCgformField.getFieldExtendJson());
            String str5 = (arrayOfString[0].length() > 0) ? arrayOfString[0] : "USERNAME";
            String str6 = (arrayOfString[1].length() > 0) ? arrayOfString[1] : "REALNAME";
            List<DictModel> list = this.sysBaseAPI.queryTableDictItemsByCode("SYS_USER", str6, str5);
            paramMap.put(str1, list);
            onlColumn.setCustomRender(str1);
        }
        if (str3.contains("file")) {
            onlColumn.setScopedSlots(new d("fileSlot"));
        } else if (str3.contains("image")) {
            onlColumn.setScopedSlots(new d("imgSlot"));
        } else if (str3.contains("editor")) {
            onlColumn.setScopedSlots(new d("htmlSlot"));
        } else if (str3.equals("date")) {
            onlColumn.setScopedSlots(new d("dateSlot"));
        } else if (str3.equals("pca")) {
            onlColumn.setScopedSlots(new d("pcaSlot"));
        }
        if (StringUtils.isNotBlank(paramOnlCgformField.getFieldHref())) {
            String str = "fieldHref_" + str1;
            onlColumn.setHrefSlotName(str);
            paramList.add(new HrefSlots(str, paramOnlCgformField.getFieldHref()));
        }
        if ("1".equals(paramOnlCgformField.getSortFlag()))
            onlColumn.setSorter(true);
        String str4 = paramOnlCgformField.getFieldExtendJson();
        if (oConvertUtils.isNotEmpty(str4) && str4.indexOf("showLength") > 0) {
            JSONObject jSONObject = JSON.parseObject(str4);
            if (jSONObject != null && jSONObject.get("showLength") != null)
                onlColumn.setShowLength(oConvertUtils.getInt(jSONObject.get("showLength")));
        }
        return onlColumn;
    }

    private List<OnlColumn> a(OnlCgformHead paramOnlCgformHead, Map<String, List<DictModel>> paramMap, List<HrefSlots> paramList, Map<String, Integer> paramMap1) {
        int i = paramOnlCgformHead.getTableType();
        ArrayList<OnlColumn> arrayList = new ArrayList<>();
        if (i == 2) {
            String str = paramOnlCgformHead.getSubTableStr();
            if (str != null && !"".equals(str)) {
                String[] arrayOfString = str.split(",");
                for (String str1 : arrayOfString) {
                    LambdaQueryWrapper<OnlCgformHead> lambdaQueryWrapper = new LambdaQueryWrapper<OnlCgformHead>()
                            .eq(OnlCgformHead::getTableName, str1);
                    OnlCgformHead onlCgformHead = this.onlCgformHeadService.getOne(lambdaQueryWrapper);
                    if (onlCgformHead != null) {
                        List<OnlCgformField> list = b(onlCgformHead.getId());
                        for (OnlCgformField onlCgformField : list) {
                            if (1 != onlCgformField.getIsShowList())
                                continue;
                            String str2 = onlCgformField.getDbFieldName();
                            if ("id".equals(str2))
                                continue;
                            Integer integer = paramMap1.get(str2);
                            if (integer == null) {
                                paramMap1.put(str2, 1);
                            } else {
                                paramMap1.put(str2, integer.intValue() + 1);
                            }
                            OnlColumn onlColumn = a(onlCgformField, paramMap, paramList);
                            onlColumn.setTableName(onlCgformHead.getTableName());
                            arrayList.add(onlColumn);
                        }
                    }
                }
            }
        }
        return arrayList;
    }
}